package org.llc.common.starter.handle;

import lombok.extern.slf4j.Slf4j;
import org.llc.common.model.Result;
import org.llc.common.starter.util.Oauth2ExceptionMessageUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.DefaultThrowableAnalyzer;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.InsufficientScopeException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
import org.springframework.security.web.util.ThrowableAnalyzer;
import org.springframework.stereotype.Component;
import org.llc.common.starter.constants.Oauth2ExceptionEnum;

/**
 * 自定义异常翻译
 *
 * @author llc
 * @date 2019/12/9 9:59
 * @since 1.0.0
 */
@Slf4j
@Component("oauth2WebResponseExceptionTranslator")
public class Oauth2WebResponseExceptionTranslator implements WebResponseExceptionTranslator {

    private ThrowableAnalyzer throwableAnalyzer = new DefaultThrowableAnalyzer();

    /**
     * 无效的刷新令牌{@value}
     */
    private static final String INVALID_REFRESH_TOKEN = "Invalid refresh token";

    /**
     * 无效的授权码{@value}
     */
    private static final String INVALID_AUTHORIZATION_CODE = "Invalid authorization code";

    /**
     * 无效的准予(授权码或refresh token无效){@value}
     */
    private static final String INVALID_GRANT = "invalid_grant";

    @Override
    public ResponseEntity<Result> translate(Exception e) {

        // Try to extract a SpringSecurityException from the stacktrace
        Throwable[] causeChain = throwableAnalyzer.determineCauseChain(e);

        // 异常栈获取 OAuth2Exception 异常
        OAuth2Exception ase = (OAuth2Exception) throwableAnalyzer.getFirstThrowableOfType(
                OAuth2Exception.class, causeChain);
        return handleOauth2Exception(ase);
    }

    /**
     * 处理认证异常
     *
     * @param e 认证异常详情
     * @return org.springframework.http.ResponseEntity<org.llc.common.model.Result>
     * @author llc
     * @date 2020/3/9 12:18
     */
    private ResponseEntity<Result> handleOauth2Exception(OAuth2Exception e) {

        int status = e.getHttpErrorCode();
        HttpHeaders headers = new HttpHeaders();
        headers.set("Cache-Control", "no-store");
        headers.set("Pragma", "no-cache");
        if (status == HttpStatus.UNAUTHORIZED.value() || (e instanceof InsufficientScopeException)) {
            headers.set("WWW-Authenticate", String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, e.getSummary()));
        }
        // 异常信息
        String message = e.getMessage();

        // 错误结果处理
        Result result = null;
        // 无效的准予
        if (INVALID_GRANT.equals(e.getOAuth2ErrorCode())) {
            // refresh token无效
            if(message.contains(INVALID_REFRESH_TOKEN)){
                result = Result.failed(Oauth2ExceptionEnum.INVALID_GRANT_REFRESH_TOKEN.getCode(), Oauth2ExceptionEnum.INVALID_GRANT_REFRESH_TOKEN.getMsg()+ Oauth2ExceptionMessageUtil.getExceptionMessage(message));
            }
            // 授权码无效
            else if(message.contains(INVALID_AUTHORIZATION_CODE)){
                result = Result.failed(Oauth2ExceptionEnum.INVALID_GRANT_AUTHORIZATION_CODE.getCode(), Oauth2ExceptionEnum.INVALID_GRANT_AUTHORIZATION_CODE.getMsg()+Oauth2ExceptionMessageUtil.getExceptionMessage(message));
            }
            // 其他授予无效
            else{
                result = Result.failed(Oauth2ExceptionEnum.INVALID_GRANT.getCode(), message);
            }
        } else {
            // 根绝异常msg返回确定的结果
            for (Oauth2ExceptionEnum oauth2ExceptionEnum:Oauth2ExceptionEnum.values()) {
                if(oauth2ExceptionEnum.getMsg().equals(message)){
                    result = Result.failed(oauth2ExceptionEnum.getCode(), oauth2ExceptionEnum.getMsg());
                    break;
                }
            }
            // 未知异常
            if(null == result){
                // 未知OAUTH认证异常
                result = Result.failed(Oauth2ExceptionEnum.OAUTH_EXCEPTION.getCode(), Oauth2ExceptionEnum.OAUTH_EXCEPTION.getMsg());
            }
        }
        log.error("认证异常详情" + result.getRespMsg());
        return new ResponseEntity<>(result, headers, HttpStatus.OK);
    }
}
